package initialize

import (
	"bottle/global"
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"go.uber.org/zap"
)

var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
	fmt.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
}

var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
	fmt.Println("Connected")
}

var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
	fmt.Printf("Connect lost: %v", err)
}

func Mqtt() {
	mqttCfg := global.GVA_CONFIG.Mqtt
	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("tcp://%s:%d", mqttCfg.Broker, mqttCfg.Port))
	opts.SetClientID(mqttCfg.ClientID)
	opts.SetUsername(mqttCfg.Username)
	opts.SetPassword(mqttCfg.Password)
	opts.SetDefaultPublishHandler(messagePubHandler)
	opts.OnConnect = connectHandler
	opts.OnConnectionLost = connectLostHandler
	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		global.GVA_LOG.Error("mqtt connect  failed, err:", zap.Error(token.Error()))
	} else {
		global.GVA_LOG.Info("mqtt connect  success:")
		global.GVA_MQTT = client
	}

}
